package com.fzu.ess.common.service.Impl;

import com.fzu.ess.common.Const;
import com.fzu.ess.common.Model.FileInputModel;
import com.fzu.ess.common.service.UploadService;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.UUID;

/**
 * Created by ercha on 2015/10/28.
 */
@Service
public class UploadServiceImpl implements UploadService {
    public FileInputModel upload(HttpServletRequest request, String inputName){
        FileInputModel fileInputModel = new FileInputModel();

        //如果没有传入 inputName，默认为 "file"
        if(inputName==null || inputName.length()<1){
            inputName = "file";
        }

        String filename = null;
        String extension = null;
        try {
            MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
            MultipartFile file = mr.getFile(inputName);    //与 input 的 name 一致
            InputStream is = file.getInputStream();
            //获取后缀名
            String ofn = file.getOriginalFilename();
            extension = ofn.substring(ofn.indexOf("."));


            //以 user.home/images/year/month/day 为路径存储
            StringBuilder separator = new StringBuilder(File.separator);
            StringBuilder path = new StringBuilder();
            path.append(System.getProperty("user.home")).append(Const.IMAGE_PATH);

            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            String month = calendar.get(Calendar.MONTH) + "";
            String day = calendar.get(Calendar.DAY_OF_MONTH) + "";
            if(month.length() < 2){
                month = "0" + month;
            }
            if(day.length() < 2){
                day = "0" + day;
            }
            path.append(year).append(separator)
                    .append(month).append(separator)
                    .append(day).append(separator);

            //如果路径不存在则创建
            mkdir(path.toString());

            //以 6位日期 + uuid.后缀名 保存
            filename = year + month + day + UUID.randomUUID().toString();
            FileOutputStream fos = new FileOutputStream(path + filename + extension);
            byte[] b = new byte[1024];
            while((is.read(b)) != -1){
                fos.write(b);
            }
            is.close();
            fos.close();

            //生成各尺寸图片
            getThumbnail(path.toString(), filename, extension);
        } catch (IOException ioe){
            ioe.printStackTrace();
            fileInputModel.setError("上传失败！");
        } catch (Exception e){
            e.printStackTrace();
        }
        fileInputModel.setUrl(filename + extension);
        return fileInputModel;
    }

    private boolean mkdir(String path){
        File f;
        //不能直接用 \ 来 split，因为需要转义，所以用 \\
        String separator = File.separator;
        if(separator.equals("\\")){
            separator += separator;
        }
        String []paths = path.split(separator);
        StringBuilder p = new StringBuilder();
        try {
            for (String i : paths) {
                p.append(i).append(separator);

                f = new File(p.toString());
                if (!f.exists() && !f.isDirectory()) {
//                    System.out.println("不存在路径：" + f);
                    if (!f.mkdir()) {
                        System.out.println("创建路径失败!");
                        return false;
                    }
                }
            }
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private void getThumbnail(String path, String filename, String extension) throws IOException {
        //大: 440*440，名称前缀 "@l"
        //中: 220*220，名称前缀 "@m"
        //小: 110*110，名称前缀 "@s"

        final int[] sz = {220, 110, 50};

        for(int i=0; i<Const.IMAGE_PREFIX.length; ++i){
            Thumbnails.of(new File(path + filename + extension))
                    .size(sz[i], sz[i]+(i==2?0:100))
                    .keepAspectRatio(false)
                    .toFile(new File(path + Const.IMAGE_PREFIX[i] + filename + extension));
        }
    }
}


